//
//  GruphotoCameraViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/21/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "GruphotoCameraViewController.h"
#import "GruphotoAppDelegate.h"
#import "User.h"

@interface GruphotoCameraViewController ()

@end

@implementation GruphotoCameraViewController
@synthesize imagePicker, takedImageView, eventId;
@synthesize flashModeButton, filtersScrollView, decideView, takeView, changeCameraView, effectsView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    filtersScrollView.contentSize = CGSizeMake(400, 63);
    takedImageView.transform = CGAffineTransformMakeScale(1.25299, 1.25299);
    flashMode = UIImagePickerControllerCameraFlashModeAuto;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.flashModeButton = nil;
    self.takedImageView = nil;
    self.filtersScrollView = nil;
    self.effectsView = nil;
    self.changeCameraView = nil;
    self.decideView = nil;
    self.takeView = nil;
}

- (void)dealloc {
    self.imagePicker = nil;
    [filtersScrollView release];
    [effectsView release];
    [changeCameraView release];
    [decideView release];
    [takeView release];
    [flashModeButton release];
    [takedImageView release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Action methods
- (IBAction)changeFlashMode:(id)sender {
//    if (![UIImagePickerController isFlashAvailableForCameraDevice:UIImagePickerControllerCameraDeviceRear] || ![UIImagePickerController isFlashAvailableForCameraDevice:UIImagePickerControllerCameraDeviceFront]) {
//        UIAlertView *alertView = [[UIAlertView alloc]
//                                  initWithTitle:NSLocalizedString(@"Warning message", @"")
//                                  message:NSLocalizedString(@"Flash is not available on this device", @"")
//                                  delegate:nil
//                                  cancelButtonTitle:NSLocalizedString(@"OK", @"")
//                                  otherButtonTitles:nil];
//        [alertView show];
//        [alertView release];
//        return;
//    }
    
    if (flashMode == UIImagePickerControllerCameraFlashModeAuto) {
        flashMode = UIImagePickerControllerCameraFlashModeOn;
        [UIView animateWithDuration:0.2 animations:^{
            [flashModeButton setImage:[UIImage imageNamed:@"button_flash_on.png"] forState:UIControlStateNormal];
        }];
    }
    else if (flashMode == UIImagePickerControllerCameraFlashModeOn) {
        flashMode = UIImagePickerControllerCameraFlashModeOff;
        [UIView animateWithDuration:0.2 animations:^{
            [flashModeButton setImage:[UIImage imageNamed:@"button_flash_off.png"] forState:UIControlStateNormal];
        }];
    }
    else if (flashMode == UIImagePickerControllerCameraFlashModeOff) {
        flashMode = UIImagePickerControllerCameraFlashModeAuto;
        [UIView animateWithDuration:0.2 animations:^{
            [flashModeButton setImage:[UIImage imageNamed:@"button_flash_auto.png"] forState:UIControlStateNormal];
        }];
    }
}

- (IBAction)changeCameraDevice:(id)sender {
    if (imagePicker.cameraDevice == UIImagePickerControllerCameraDeviceFront) {
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    }
    else {
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }
}

- (IBAction)closeCamera:(id)sender {
    [imagePicker dismissModalViewControllerAnimated:YES];
}

- (IBAction)takePicture:(id)sender {
    [imagePicker takePicture];
}

- (IBAction)showImagePicker:(id)sender {
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}

- (IBAction)retakeImage:(id)sender {
    [self approveImageAndUpload:nil];
}

- (IBAction)approveImageAndUpload:(id)sender {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    [params setObject:[NSString stringWithFormat:@"%d", eventId] forKey:kEventId];
    NSData *imageData = UIImageJPEGRepresentation(takedImageView.image, 1.0);
    [params setObject:imageData forKey:kPhoto];
    
    [TNHRequestHelper sendPostRequest:kUploadPhotoToEventUrl
                              withTag:RequestTagUploadPhoto
                               params:params
                             delegate:self];
    
    takedImageView.image = nil;
    [UIView animateWithDuration:0.4 animations:^{
        CGRect frame = effectsView.frame;
        frame.origin.y = -frame.size.height;
        effectsView.frame = frame;
        frame = decideView.frame;
        frame.origin.y = [Global screenHeight];
        decideView.frame = frame;
        frame = filtersScrollView.frame;
        frame.origin.y = [Global screenHeight];
        filtersScrollView.frame = frame;
    } completion:^(BOOL finished) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.4];
        
        takedImageView.hidden = YES;
        CGRect frame = changeCameraView.frame;
        frame.origin.y = 0;
        changeCameraView.frame = frame;
        
        frame = takeView.frame;
        frame.origin.y = [Global screenHeight] - frame.size.height;
        takeView.frame = frame;
        [UIView commitAnimations];
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    takedImageView.image = image;
    
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [UIView animateWithDuration:0.4 animations:^{
        CGRect frame = changeCameraView.frame;
        frame.origin.y = -frame.size.height;
        changeCameraView.frame = frame;
        
        frame = takeView.frame;
        frame.origin.y = [Global screenHeight] + 22;
        takeView.frame = frame;
        
    } completion:^(BOOL finished) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.4];
        takedImageView.hidden = NO;
        
        CGRect frame = effectsView.frame;
        frame.origin.y = 0;
        effectsView.frame = frame;
        
        frame = decideView.frame;
        frame.origin.y = [Global screenHeight] - frame.size.height;
        decideView.frame = frame;
        
        frame = filtersScrollView.frame;
        frame.origin.y = 374.0;
        filtersScrollView.frame = frame;
        
        [UIView commitAnimations];        
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"data: %@", request.responseString);
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"Failed: %@", request.error.description);
}

@end
